/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.com.app.knock;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import z.lib.base.BaseActivity;
import z.lib.base.BaseFragment;
import z.lib.base.BaseUtils;
import z.lib.base.LogUtils;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.knock.app.R;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParsePushBroadcastReceiver;
import com.parse.ParseQuery;
import com.parse.SaveCallback;

/**
 * Handling of GCM messages.
 */
public class GcmBroadcastReceiverParse extends ParsePushBroadcastReceiver {
	static final String TAG = "GCMDemo";
	final static String KEY_USER_INFO = "user_id";
	@Override
	protected Notification getNotification(Context context, Intent intent) {
		Bundle extras = intent.getExtras();
		String jsonData = extras.getString("com.parse.Data");
		String title = "Knock";
		String message = "";
		String customdata = "";
		if (jsonData != null) {
			try {
				JSONObject data = new JSONObject(jsonData);
				message = data.getString("alert");
				if(data.has("customdata")){
					customdata = data.getString("customdata");
				}
				
				BaseUtils.playMedia(context,R.raw.knock);
				Intent pupInt = new Intent(context, ShowPopUp.class);
				pupInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
				pupInt.putExtra("data_push", message);
				pupInt.putExtra("customdata", customdata);
				context.getApplicationContext().startActivity(pupInt);
			} catch (JSONException e) {
				Log.e(TAG, "Error parsing json data");
			}
		} else {
			Log.e(TAG, "cannot find notification data");
		}

//		PendingIntent contentIntent = null;
//		Intent notificationIntent = new Intent(context, MainActivity.class);
//		contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
//		Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
//		// Vibrate for 300 milliseconds
//		v.vibrate(300);
//		BaseUtils.playMedia(context,R.raw.knock);
//		NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher).setContentTitle(title).setContentText(message)
//				.setContentIntent(contentIntent).setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true).setStyle(new NotificationCompat.BigTextStyle().bigText(message));
		return null;/*builder.build();*/
	}

	public static void registerUserInfo(Context context){
//		try {
//			String Parse_app_key = context.getResources().getString(R.string.parse_app_key);
//			String Parse_client_key = context.getResources().getString(R.string.parse_client_key);
//			Parse.initialize(context, Parse_app_key, Parse_client_key);
//			String user_id = "";//
//			ParseInstallation.getCurrentInstallation().put(KEY_USER_INFO, user_id);
//			ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
//				@Override
//				public void done(ParseException e) {
//					if (e == null) {
//						// OK
//						LogUtils.e(TAG,"registerUserInfo Done");
//					} else {
//						// Err
//						LogUtils.e(TAG,"registerUserInfo Err");
//						e.printStackTrace();
//					}
//				}
//			});
//		} catch (Exception e2) {
//			e2.printStackTrace();
//		}
	}
	
	public static void unregisterUserInfo(Context context){
//		try {
//			String Parse_app_key = context.getResources().getString(R.string.parse_app_key);
//			String Parse_client_key = context.getResources().getString(R.string.parse_client_key);
//			Parse.initialize(context, Parse_app_key, Parse_client_key);
//			ParseInstallation.getCurrentInstallation().put(KEY_USER_INFO, "");
//			ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
//				@Override
//				public void done(ParseException e) {
//					if (e == null) {
//						// OK
//						LogUtils.e(TAG,"unregisterUserInfo Done");
//					} else {
//						// Err
//						LogUtils.e(TAG,"unregisterUserInfo Err");
//						e.printStackTrace();
//					}
//				}
//			});
//		} catch (Exception e2) {
//			e2.printStackTrace();
//		}
	}
	
	public static void loginDevice(final Context context, final String name){
//		ParseQuery<ParseObject> query = ParseQuery.getQuery("DeviceList");
//		query.whereEqualTo("area_device", name);
//		LogUtils.e("score", "Error: ===========");
//		query.findInBackground(new FindCallback<ParseObject>() {
//		    public void done(List<ParseObject> scoreList, ParseException e) {
//		        if (e == null) {
//		        	LogUtils.e("score", "Retrieved " + scoreList.size() + " scores");
//		            if(scoreList.size() <= 0){
//		            	BaseUtils.showDialog(context, "user name incorrect!" );
//		            }else{
//		            	scoreList.get(0).put("objectId_device", KnockApplication.objectId);
//		        		scoreList.get(0).saveInBackground(new SaveCallback() {
//		    				@Override
//		    				public void done(ParseException e) {
//		    					if (e == null) {
//		    						// OK
//		    						KnockApplication.userName = name;
//		    						startFragment(new Friend_oldFragment(), null, context);
//		    						LogUtils.e(TAG,"addInfo2 Done");
//		    					} else {
//		    						// Err
//		    						LogUtils.e(TAG,"addInfo2 Err");
//		    						e.printStackTrace();
//		    					}
//		    				}
//		    			});
//		            }
//		        } else {
//		        	LogUtils.e("score", "Error: " + e.getMessage());
//		        }
//		    }
//		});
	}
	
	public static void addDevice(final Context context, final String name){
//		ParseQuery<ParseObject> query = ParseQuery.getQuery("DeviceList");
//		query.whereEqualTo("area_device", name);
//		LogUtils.e("score", "Error: ===========");
//		query.findInBackground(new FindCallback<ParseObject>() {
//		    public void done(List<ParseObject> scoreList, ParseException e) {
//		        if (e == null) {
//		        	LogUtils.e("score", "Retrieved " + scoreList.size() + " scores");
//		            if(scoreList.size() <= 0){
//		            	ParseObject addObject = new ParseObject("DeviceList");
//		            	addObject.put("area_device", name);
//		            	addObject.put("objectId_device", KnockApplication.objectId);
//		            	addObject.saveInBackground(new SaveCallback() {
//		    				@Override
//		    				public void done(ParseException e) {
//		    					if (e == null) {
//		    						// OK
//		    						startFragment(new Friend_oldFragment(), null, context);
//		    						LogUtils.e(TAG,"addInfo1 Done");
//		    					} else {
//		    						// Err
//		    						LogUtils.e(TAG,"addInfo1 Err");
//		    						e.printStackTrace();
//		    					}
//		    				}
//		    			});
//		            }else{
//		            	scoreList.get(0).put("objectId_device", KnockApplication.objectId);
//		        		scoreList.get(0).saveInBackground(new SaveCallback() {
//		    				@Override
//		    				public void done(ParseException e) {
//		    					if (e == null) {
//		    						// OK
//		    						startFragment(new Friend_oldFragment(), null, context);
//		    						LogUtils.e(TAG,"addInfo2 Done");
//		    					} else {
//		    						// Err
//		    						LogUtils.e(TAG,"addInfo2 Err");
//		    						e.printStackTrace();
//		    					}
//		    				}
//		    			});
//		            }
//		        } else {
//		        	LogUtils.e("score", "Error: " + e.getMessage());
//		        }
//		    }
//		});
	}
	
	public static void findDevice(final Context context, final String name){
//		ParseQuery<ParseObject> query = ParseQuery.getQuery("DeviceList");
//		query.whereEqualTo("area_device", name);
//		query.findInBackground(new FindCallback<ParseObject>() {
//		    public void done(List<ParseObject> scoreList, ParseException e) {
//		        if (e == null) {
//		        	LogUtils.e("score", "Retrieved " + scoreList.size() + " scores");
//		            if(scoreList.size() > 0){
//		            	startFragment(new Friend_oldFragment(), null, context);
//		            }
//		        } else {
//		        	LogUtils.e("score", "Error: " + e.getMessage());
//		        }
//		    }
//		});
	}
	
	public final static void startFragment(BaseFragment baseFragment, Bundle extras, Context context) {
		if (context instanceof BaseActivity) {
			try {
				((BaseActivity) context).startFragment(baseFragment, extras);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}